from django.http import HttpResponse
from one2many.models import *


def add_user_type(request):
    user_types = ['青铜', '白银', '黄金', '钻石']
    for t in user_types:
        UserType.objects.create(name=t)
    return HttpResponse('添加成功')


def add_user(request):
    for i in range(1, 11):
        # User.objects.create(name=f'张三{i}', age=10+i, user_type_id=i%4+1)
        User.objects.create(name=f'张三{i}', age=10+i, user_type=UserType.objects.get(pk = i%4+1))
    return HttpResponse('添加成功')


def del_user_type(request):
    UserType.objects.filter(id=4).delete()
    return HttpResponse('删除成功')


def del_user(request):
    User.objects.filter(id=10).delete()
    return HttpResponse('删除成功')


def update_user_type(request):
    UserType.objects.filter(id=1).update(name="青青")
    return HttpResponse('修改成功')


def update_user(request):
    User.objects.filter(id=1).update(user_type_id=1)
    return HttpResponse('修改成功')


def get_user_type(request):
    """反向查询"""
    utype = UserType.objects.get(id=1)
    content = f"utype.id: {utype.id}, utype.name: {utype.name}<br>"
    print(utype.user_set.all())
    # users = User.objects.filter(user_type=UserType.objects.get(name="青铜"))
    # users = User.objects.filter(user_type_id=1)
    # users = User.objects.filter(user_type__name="黄金")
    # print(users)
    return HttpResponse(content)


def get_user(request):
    """正向查询"""
    user = User.objects.get(id=1)
    content = (f"user.id: {user.id}, user.name: {user.name}, user.age: {user.age}, user.user_type_id: {user.user_type_id}<br>"
               f"user.user_type.name:{user.user_type.name}, user.user_type.id:{user.user_type.id}")
    return HttpResponse(content)
